"""
持仓量因子（用变动率吧 用持仓量的变动除以总持仓量）
单根k线变动  累计5根k线变动 累计30跟k线变动
"""
import pandas as pd
import rqdatac as rq
from datetime import timedelta
from ..utility import make_domaint_time_dict


def self_get_factor_df(sec_id):
    symbol_time_dict = make_domaint_time_dict(sec_id)
    result_df = {}
    for symbol, time_dict in symbol_time_dict.items():
        prices = rq.get_price(symbol, start_date="20220801", end_date="20231116", frequency="1m",
                              fields="open_interest", expect_df=False)
        prices.index -= timedelta(minutes=1)
        p_r = (prices - prices.shift(5)) / prices
        p_r = p_r[time_dict["start"]: time_dict["last"]]
        symbol_df = pd.DataFrame(p_r)
        symbol_df["symbol"] = symbol
        result_df[symbol] = symbol_df
    return pd.concat(list(result_df.values()))


def get_factor_df(sec_id, prices):
    print(sec_id, __file__)
    for window in [1, 5, 30]:
        p_r = (prices["open_interest"] - prices["open_interest"].shift(window)) / prices["open_interest"]
        prices[f"position_{window}"] = p_r
    return prices
